﻿using System.Configuration;
using System.IO;
using System.Linq;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using GdNet.Integrations.NHibernate.Interceptors;
using GdNet.Integrations.NHibernate.SessionManagement;
using NHibernate;

namespace GdNet.Integrations.Castle.Facilities
{
    public abstract class AbstractPersistenceFacility : AbstractFacility
    {
        protected override void Init()
        {
            var builder = CreateSessionFactoryBuilder();
            Kernel.Register(Component.For<ISessionFactory>().UsingFactoryMethod(builder.BuildSessionFactory).LifestyleSingleton());

            RegisterSession();
        }

        private SessionFactoryBuilder CreateSessionFactoryBuilder()
        {
            var configurationFile = Path.Combine(GetCurrentDirectory(), ConfigurationManager.AppSettings["NHibernateConfigurationFile"]);
            var builder = SessionFactoryBuilder.NewInstance()
                                               .UseConfigurationFile(configurationFile)
                                               .AddInterceptor(new EntityWithModificationInterceptor());

            var mappingFiles = ConfigurationManager.AppSettings["MappingFiles"];
            mappingFiles.Split(';').ToList().ForEach(file =>
                {
                    var filePath = Path.Combine(GetCurrentDirectory(), file);
                    builder.WithMappingFile(filePath);
                });

            return builder;
        }

        protected abstract void RegisterSession();
        protected abstract string GetCurrentDirectory();
    }
}
